package com.github.kezhenxu94.playground.java.concurrent.executor;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 为每一个任务创建一个线程与使用 Executor 的性能比较
 * 
 * @author kezhenxu
 *
 */
public class ThreadPerTaskVSExecutor {

	static class SocketHandler implements Runnable {
		private Socket socket;

		public SocketHandler(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
				writer.write("HTTP/1.0 200 OK\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) throws Exception {
		Executor exec = Executors.newCachedThreadPool();
		try (ServerSocket server = new ServerSocket(9090);) {
			while (true) {
				Socket socket = server.accept();
//				new Thread(new SocketHandler(socket)).start();
				exec.execute(new SocketHandler(socket));
			}
		}
	}
}
